﻿using Cartographer.Extensions;
using System.Collections.Generic;
using System.Xml.Linq;

namespace Cartographer.Tiled
{
	public class TiledMap
	{
		public string Version { get; set; }
		public string Orientation { get; set; }
		public int Width { get; set; }
		public int Height { get; set; }
		public int TileWidth { get; set; }
		public int TileHeight { get; set; }
		public string BackgroundColor { get; set; }

		public List<TiledProperty> Properties { get; set; }
		public List<TiledTileset> Tilesets { get; set; }
		public List<TiledObjectGroup> ObjectGroups { get; set; }
		public List<TiledLayer> Layers { get; set; }

		public TiledMap()
		{
			Properties = new List<TiledProperty>();
			Tilesets = new List<TiledTileset>();
			ObjectGroups = new List<TiledObjectGroup>();
			Layers = new List<TiledLayer>();
		}

		public TiledMap(XDocument document)
		{
			Properties = new List<TiledProperty>();
			Tilesets = new List<TiledTileset>();
			ObjectGroups = new List<TiledObjectGroup>();
			Layers = new List<TiledLayer>();

			var map = document.Element("map");
			Version = map.GetAttribute<string>("version");
			Orientation = map.GetAttribute<string>("orientation");
			Width = map.GetAttribute<int>("width");
			Height = map.GetAttribute<int>("height");
			TileWidth = map.GetAttribute<int>("tilewidth");
			TileHeight = map.GetAttribute<int>("tileheight");
			BackgroundColor = map.GetAttribute<string>("backgroundcolor");

			var tilesets = map.Elements("tileset");
			foreach (var data in tilesets)
			{
				Tilesets.Add(new TiledTileset(data));
			}

			var layers = map.Elements("layer");
			foreach (var data in layers)
			{
				Layers.Add(new TiledLayer(data));
			}
		}
	}
}